package com.story.modular.app.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.story.common.Util.PageResult;
import com.story.common.exception.BizExceptionEnum;
import com.story.common.exception.BussinessException;
import com.story.common.persistence.dao.BannerMapper;
import com.story.common.persistence.dao.VedioCategoryMapper;
import com.story.common.persistence.model.*;
import com.story.core.base.controller.BaseController;
import com.story.modular.app.constrant.QueryListForm;
import com.story.modular.app.dao.ApphomeZhuanjiDao;
import com.story.modular.app.dao.BannerDao;
import com.story.modular.app.dao.VedioCategoryDao;
import com.story.modular.app.service.AppHomeService;
import com.story.modular.app.service.ICategoryclassService;
import com.story.modular.app.service.IPageclassService;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;

import javax.validation.Valid;
import java.util.*;

/**
 * 首页控制器
 *
 * @author fengshuonan
 * @Date 2020-05-13 16:35:06
 */
@Api(value = "app首页icon图片", description = "app首页icon图片")
@Controller
@RequestMapping("/apphome")
public class ApphomeController extends BaseController {

    private String PREFIX = "/app/apphome/";

    @Autowired
    private AppHomeService appHomeService;
    @Autowired
    private IPageclassService pageclassService;
    @Autowired
    private ICategoryclassService iCategoryclassService;
    @Autowired
    private BannerMapper bannerMapper;
    @Autowired
    private VedioCategoryDao vedioCategoryDao;
    @Autowired
    private ApphomeZhuanjiDao apphomeZhuanjiDao;
    @Autowired
    private VedioCategoryMapper vedioCategoryMapper;
    @Autowired
    private BannerDao bannerDao;

    /**
     * 跳转到首页首页
     */
    @RequestMapping("")
    public String index(Model model) {
        CategoryClass categoryClass=new CategoryClass();
        pageclass pageclass=new pageclass();
        List<CategoryClass> cateclasss=iCategoryclassService.quyerList(categoryClass);
        List<pageclass> pageclasses=pageclassService.quyerList(pageclass);

        model.addAttribute("categorys",cateclasss);
        model.addAttribute("pages",pageclasses);
        return PREFIX + "apphome.html";
    }

    /**
     * 跳转到添加首页
     */
    @RequestMapping("/apphome_add")
    public String apphomeAdd(Model model) {

        List<Banner> bannerList = bannerMapper.selectList(new EntityWrapper<Banner>().eq("type",0));
        List<Map<String,Object>> bannerMapList = new ArrayList<>();
        for(Banner banner : bannerList) {
            Map<String,Object> map = new HashMap<>(16);
            map.put("id",banner.getId());
            map.put("name",banner.getName());
            bannerMapList.add(map);
        }
        //查询所有专辑
        List<Map<String,Object>> categoryList = vedioCategoryDao.getAllCategory(0);
        if(categoryList.isEmpty()) {
            throw new BussinessException(BizExceptionEnum.CATES_NULL);
        }

        CategoryClass categoryClass=new CategoryClass();
        pageclass pageclass=new pageclass();
        List<CategoryClass> cateclasss=iCategoryclassService.quyerList(categoryClass);
        List<pageclass> pageclasses=pageclassService.quyerList(pageclass);

        model.addAttribute("bannerList",bannerMapList);
        model.addAttribute("cateList",categoryList);
        model.addAttribute("categorys",cateclasss);
        model.addAttribute("pages",pageclasses);
        return PREFIX + "apphome_add.html";
    }

    /**
     * 跳转到修改首页
     */
    @RequestMapping("/apphome_update/{apphomeId}")
    public String apphomeUpdate(@PathVariable Integer apphomeId, Model model) {
        apphome apphome=appHomeService.queryObject(apphomeId);

        //把专辑转换成中文  从新获取分类name
        String[] zhuanjis=apphome.getZhuanji().split(",");
        Integer[] cateNameInts = new Integer[zhuanjis.length];
        for (int j = 0; j < zhuanjis.length; j++) {
            if (!zhuanjis[j].equals("")){
                cateNameInts[j] = Integer.parseInt(zhuanjis[j]);
                List<Integer> cateIds = Arrays.asList(cateNameInts);
                Set<Integer> cateIdSet = new HashSet<>(cateIds);
                cateIds = new ArrayList<>(cateIdSet);
                apphome.setZhuanjiName(vedioCategoryDao.getCateNameById(cateIds));
            }

        }
        if (!"".equals(apphome.getType()) && apphome.getType()!=null){
            Banner banner2 = bannerDao.selectBannerById(Integer.parseInt(apphome.getType()));
            apphome.setFenleiName(banner2.getName());
        }



        //查询该音频的信息
        //查询所有专辑和对应年龄段,处理是否选中
        List<VedioCategory> categoryList1 = vedioCategoryMapper.selectList(new EntityWrapper<VedioCategory>().eq("resType",0));
        List<Map<String,Object>> cateList = new ArrayList<Map<String,Object>>();
        for (VedioCategory vedioCategory : categoryList1) {
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("name",vedioCategory.getName());
            map.put("id",vedioCategory.getId());
            boolean flag = false;
            if(StringUtils.isNotBlank(apphome.getZhuanji())) {
                String[] cateIds = (apphome.getZhuanji().split(","));
                for (int i = 0; i < cateIds.length; i++) {
                    if(vedioCategory.getId() == Integer.parseInt(cateIds[i])) {
                        flag = true;
                        map.put("checked","true");
                    } else {
                        continue;
                    }
                }
            }
            if(!flag) {
                map.put("checked","false");
            }
            cateList.add(map);
        }


        List<Banner> bannerList = bannerMapper.selectList(new EntityWrapper<Banner>().eq("type",0));
        List<Map<String,Object>> bannerMapList = new ArrayList<>();
        for(Banner banner : bannerList) {
            Map<String,Object> map = new HashMap<>(16);
            map.put("id",banner.getId());
            map.put("name",banner.getName());
            boolean flag = false;
            if(StringUtils.isNotBlank(apphome.getType())) {
                String[] cateIds = (apphome.getType().split(","));
                for (int i = 0; i < cateIds.length; i++) {
                    if(banner.getId() == Integer.parseInt(cateIds[i])) {
                        flag = true;
                        map.put("checked","true");
                    } else {
                        continue;
                    }
                }
            }
            if(!flag) {
                map.put("checked","false");
            }
            bannerMapList.add(map);
        }
        //查询所有专辑
        List<Map<String,Object>> categoryList = vedioCategoryDao.getAllCategory(0);
        //定义一个对象


        if(categoryList.isEmpty()) {
            throw new BussinessException(BizExceptionEnum.CATES_NULL);
        }

        CategoryClass categoryClass=new CategoryClass();
        pageclass pageclass=new pageclass();
        List<CategoryClass> cateclasss=iCategoryclassService.quyerList(categoryClass);
        List<pageclass> pageclasses=pageclassService.quyerList(pageclass);

        model.addAttribute("bannerList",bannerMapList);
        model.addAttribute("cateList",categoryList);
        model.addAttribute("cateList2",cateList);
        model.addAttribute("categorys",cateclasss);
        model.addAttribute("pages",pageclasses);

        model.addAttribute("apphome",apphome);
        return PREFIX + "apphome_edit.html";
    }

    /**
     * 获取首页列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(QueryListForm queryListForm,@RequestParam(required=false,defaultValue="1") int page,
                       @RequestParam(required=false,defaultValue="10") int limit) {

//        Map<String,Object> map=new HashMap<String,Object>();
//        if (!"".equals(name) && name !=null){
//            map.put("name",name);
//        }
        Page<apphome> page1 = new Page<apphome>();

        //page.setRecords(categoryService.queryPageList(page,condition));

        page1.setCurrent(page);
        page1.setSize(limit);
        PageResult pageResult=new PageResult();
        List<Map<String,Object>> list=appHomeService.queryPageList(page1,queryListForm);
        for (int i=0;i<list.size();i++){

            if(!"".equals(list.get(i).get("zhuanji")) && (list.get(i).get("zhuanji")!=null)){
                String[] zhuanjis=((String)list.get(i).get("zhuanji")).split(",");
                Integer[] cateNameInts = new Integer[zhuanjis.length];
                for (int j = 0; j < zhuanjis.length; j++) {
                    cateNameInts[j] = Integer.parseInt(zhuanjis[j]);
                }
                List<Integer> cateIds = Arrays.asList(cateNameInts);
                Set<Integer> cateIdSet = new HashSet<>(cateIds);
                cateIds = new ArrayList<>(cateIdSet);
                list.get(i).put("zhuanjiName",vedioCategoryDao.getCateNameById(cateIds));
            }
            if (!"".equals(list.get(i).get("type")) && (list.get(i).get("type")!=null)){
                String type= (String) list.get(i).get("type");
                Banner banner2 = bannerDao.selectBannerById(Integer.parseInt(type));
                list.get(i).put("fenleiName",banner2.getName());
            }
        }

        pageResult.setData(list);
        pageResult.setCode("0");
        int total=page1.getTotal();
        System.out.println(total);
        pageResult.setCount(page1.getTotal());

        pageResult.setMsg("首页分类");
        return pageResult;
    }

    //接口app首页 分类列表
    @ApiOperation(value="首页内容分类", notes="首页内容分类接口")
    @RequestMapping(value = "/queryList",method = RequestMethod.POST)
    @ResponseBody
    public Object querylist(@ApiParam(name="传入对象",value="传入json格式",required=true) @RequestBody @Valid QueryListForm queryListForm) {
        return appHomeService.queryList(queryListForm);
    }

    /**
     * 新增首页
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(apphome apphome) {
        appHomeService.save(apphome);

        //保存首页分类与专辑的关系信息
        String[] cateVedioIds = apphome.getZhuanji().split(",");
        String[] cateVedioIds2 = apphome.getType().split(",");
        if (!cateVedioIds[0].equals(""))
        for (int i = 0; i < cateVedioIds.length; i++) {
            apphomezhuanjiVo cateVedio = new apphomezhuanjiVo();
            cateVedio.setApphomeId(apphome.getId());
            cateVedio.setZhuanjiId(Integer.parseInt(cateVedioIds[i]));
            cateVedio.setType(1);//专辑id
            apphomeZhuanjiDao.insert(cateVedio);
        }
        if (!cateVedioIds2[0].equals(""))
        for (int i = 0; i < cateVedioIds2.length; i++) {
            apphomezhuanjiVo cateVedio = new apphomezhuanjiVo();
            cateVedio.setApphomeId(apphome.getId());
            cateVedio.setZhuanjiId(Integer.parseInt(cateVedioIds2[i]));
            cateVedio.setType(0);//分类
            apphomeZhuanjiDao.insert(cateVedio);
        }
        return super.SUCCESS_TIP;
    }

    /**
     * 删除首页
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam(value = "ids") String ids) {
        String[] idArray=ids.split(",");
        for (int i=0;i<idArray.length;i++){
            appHomeService.delete(Integer.parseInt(idArray[i]));
        }
        return SUCCESS_TIP;
    }


    /**
     * 修改首页
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(apphome apphome) {
        appHomeService.update(apphome);
        //更改关系表
        //保存首页分类与专辑的关系信息
        apphomeZhuanjiDao.deleteByIds(apphome.getId());
        String[] cateVedioIds = apphome.getZhuanji().split(",");
        String[] cateVedioIds2 = apphome.getType().split(",");
        if (!cateVedioIds[0].equals(""))
        for (int i = 0; i < cateVedioIds.length; i++) {
            apphomezhuanjiVo cateVedio = new apphomezhuanjiVo();
            cateVedio.setApphomeId(apphome.getId());
            cateVedio.setZhuanjiId(Integer.parseInt(cateVedioIds[i]));
            cateVedio.setType(1);//专辑id
            apphomeZhuanjiDao.insert(cateVedio);
        }
        if (!cateVedioIds2[0].equals(""))
        for (int i = 0; i < cateVedioIds2.length; i++) {
            apphomezhuanjiVo cateVedio = new apphomezhuanjiVo();
            cateVedio.setApphomeId(apphome.getId());
            cateVedio.setZhuanjiId(Integer.parseInt(cateVedioIds2[i]));
            cateVedio.setType(0);//分类
            apphomeZhuanjiDao.insert(cateVedio);
        }
        return super.SUCCESS_TIP;
    }

    /**
     * 首页详情
     */
    @RequestMapping(value = "/detail")
    @ResponseBody
    public Object detail() {
        return null;
    }
}
